<?php
class DataBufferedReaderD extends CApplicationComponent{
	public $mongoOptions=array();
	protected $_mogoInstance=null;
	protected $_cache=null;
	public $cacheId='';
	protected $_sort=array();
	protected $_conds = array();
	private $_attrs = array();
	public function asc($field){
		$this->_sort[$field]=1;
		return $this;
	}	
	public function desc($field){
		$this->_sort[$field]=-1;
		return $this;
	}
	public function addL(){
		throw new Exception('addL not implents yet');
		/**
		$this->_conds.='(';
		return $this;
		**/
	}
	public function addR(){
		throw new Exception('addR not implents yet');
		/**
		$this->_conds.=')';
		return $this;
		**/
	}
	public function andCond(){
		throw new Exception('andCond not implents yet');
		/**
		$this->_conds.=' && ';
		return $this;
		**/
	}
	/**
	 * 
	 * @param 字段名 $attr
	 * @param 操作符 $operator
	 * @param 值 $value
	 */
	protected function operator($attr, $operator, $value) {
		if (!isset($this->_conds[$attr])) {
			$this->_conds[$attr] = array();
		}
		$this->_conds[$attr][$operator] = $value;
		return $this;
	}
		
	public function orCond(){
		throw new Exception('orCond not implents yet');
		/**
		$this->_conds.=' || ';
		return $this;
		**/
	}
	public function gt($attr,$value){
		return $this->operator($attr, '$gt', $value);
		/**
		if($this->_conds!=='' && $this->_conds!=='('){
			$s=mb_substr($this->_conds,-3,3,'utf-8');
			if(strpos($s,'&&')===false && strpos($s,'||')===false){
				$this->_conds.=' && ';
			}
		}
		$this->_conds .="this.{$f} > {$v}";
		return $this;
		**/
	}
	public function gte($attr,$value){
		return $this->operator($attr, '$gte', $value);
		/**
		if($this->_conds!=='' && $this->_conds!=='('){
			$s=mb_substr($this->_conds,-3,3,'utf-8');
			if(strpos($s,'&&')===false && strpos($s,'||')===false){
				$this->_conds.=' && ';
			}
		}
		$this->_conds .="this.{$f} >= {$v}";
		return $this;
		**/
	}
	public function lt($attr,$value){
		return $this->operator($attr, '$lt', $value);
		/**
		if($this->_conds!=='' && $this->_conds!=='('){
			$s=mb_substr($this->_conds,-3,3,'utf-8');
			if(strpos($s,'&&')===false && strpos($s,'||')===false){
				$this->_conds.=' && ';
			}
		}
		$this->_conds .="this.{$f} < {$v}";
		return $this;
		**/
	}
	public function lte($attr,$value){
		return $this->operator($attr, '$lte', $value);
		/**
		if($this->_conds!=='' && $this->_conds!=='('){
			$s=mb_substr($this->_conds,-3,3,'utf-8');
			if(strpos($s,'&&')===false && strpos($s,'||')===false){
				$this->_conds.=' && ';
			}
		}
		$this->_conds .="this.{$f} <= {$v}";
		return $this;
		**/
	}
	public function eq($attr,$value){
		return $this->attr($attr,$value);
		/**
		if($this->_conds!=='' && $this->_conds!=='('){
			$s=mb_substr($this->_conds,-3,3,'utf-8');
			if(strpos($s,'&&')===false && strpos($s,'||')===false){
				$this->_conds.=' && ';
			}
		}
		$this->_conds .="this.{$f} == '{$v}'";
		return $this;
		**/
	}
	public function ne($attr,$value){
		return $this->operator($attr, '$ne', $value);
		/**
		if($this->_conds!=='' && $this->_conds!=='('){
			$s=mb_substr($this->_conds,-3,3,'utf-8');
			if(strpos($s,'&&')===false && strpos($s,'||')===false){
				$this->_conds.=' && ';
			}
		}
		$this->_conds .="this.{$f} != '{$v}'";
		return $this;
		**/
	}
	public function in($attr,array $value){
		return $this->operator($attr, '$in', $value);
		/**
		if($this->_conds!=='' && $this->_conds!=='('){
			$s=mb_substr($this->_conds,-3,3,'utf-8');
			if(strpos($s,'&&')===false && strpos($s,'||')===false){
				$this->_conds.=' && ';
			}
		}
		$this->_conds=' (';
		foreach($v as $vv){
			$this->_conds .="this.{$f} == '{$vv}' || ";
		}
		$this->_conds=mb_substr($this->_conds,0,-3,'utf-8');
		$this->_conds.=' ) ';
		return $this;
		**/
	}
	public function nin($attr,array $value){
		return $this->operator($attr, '$nin', $values);
		
		/**
		if($this->_conds!=='' && $this->_conds!=='('){
			$s=mb_substr($this->_conds,-3,3,'utf-8');
			if(strpos($s,'&&')===false && strpos($s,'||')===false){
				$this->_conds.=' && ';
			}
		}
		$this->_conds=' (';
		foreach($v as $vv){
			$this->_conds .="this.{$f} == '{$vv}' && ";
		}
		$this->_conds=mb_substr($this->_conds,0,-3);
		$this->_conds.=' ) ';
		return $this;
		**/
	}
	/**
	 * 指定属性值
	 *
	 * @param string|array $nameOrAttrs 属性名或一组属性值
	 * @param string $value 属性值
	 * @return RQuery
	 */
	public function attr($nameOrAttrs, $value = null) {
		if (!is_array($nameOrAttrs)) {
			$nameOrAttrs = array( $nameOrAttrs => $value );
		}
		foreach ($nameOrAttrs as $attr => $value) {
			if ($attr == "_id" && (!is_object($value) || !($value instanceof MongoId)) && strlen($attr) == 24) {
				$value = new MongoId($value);
			}
			if (!isset($this->_attrs[$attr])) {
				$this->_attrs[$attr] = array();
			}
			if (is_array($value)) {
				$this->_attrs[$attr] = array_merge($this->_attrs[$attr], $value);
			}
			else {
				$this->_attrs[$attr][] = $value;
			}
		}
		return $this;
	}	
	public function like($attr,$value){
		return $this->attr($attr, new MongoRegex($value));
		/**
		if($this->_conds!=='' && $this->_conds!=='('){
			$s=mb_substr($this->_conds,-3,3,'utf-8');
			if(strpos($s,'&&')===false && strpos($s,'||')===false){
				$this->_conds.=' && ';
			}
		}
		$this->_conds .="this.{$f}.test(/^$v/)";
		return $this;
		**/
	}
	/**
	 * 现有查询条件的组合
	 *
	 * @return array
	 */
	protected function criteria() {
		$attrs = array();
		foreach ($this->_attrs as $attr => $values) {
			if (!empty($values)) {
				if (count($values) == 1) {
					$attrs[$attr] = $values[0];
				}
				else {
					$attrs[$attr]['$in'] = $values;
				}
			}
		}
		return array_merge($attrs, $this->_conds);
	}	
        /**
         * 分组方法仅给统计用 CounterD.php
         * @param type $tableName
         * @param array $keys
         * @return type 
         */
	public function group($tableName,array $keys){
		$initial = array("count" =>0,"title"=>'',"logo"=>"",'area_code'=>"");
		$reduce = new MongoCode("function (obj, prev) { prev.count++;prev.title=obj.title;prev.logo=obj.logo;prev.area_code=obj.area_code;}");
		if($this->_mogoInstance===null){
			$this->_mogoInstance = new DLDMongoD($this->mongoOptions['host'],$this->mongoOptions['port'],$this->mongoOptions['database']);
		}
		 return $this->_mogoInstance->group($tableName,$keys , $initial , $reduce, $options = array('condition'=>$this->criteria()) );
	}
	
	/**
	 * 复合条件查询
	 * @param unknown_type $collection  array('userid'=>123,'username'=>'zhangsan')
	 * Author yangtao 2012-08-31
	 */
	public function Complex($collection = array()){
		if(count($collection) > 0){
			foreach ($collection as $key=>$val){
				if ('userid'==$key){
					$this->eq($key, (int)$val);
				}elseif ('start' == $key) {
					$this->gte('runtime',(int)$val);
				}elseif ('end' == $key) {
					$this->lte('runtime',(int)$val);
				}else { 
					$this->like($key, "/{$val}/i");
				}
			}
		}
		return $this;
	}
	
	/**
	获得指定数据
	return array
	$query 查询数组配置
	$collection 表名
	**/
	public function findOne($collection,$fields = array()){
		try{
			if($this->_mogoInstance===null){
				$this->_mogoInstance = new DLDMongoD($this->mongoOptions['host'],$this->mongoOptions['port'],$this->mongoOptions['database']);
			}		
			$result=$this->_mogoInstance->findOne($this->criteria(),$collection,$fields);
			$this->clearCondition();
			return $result;
		}catch(Exception $ex){
			//throw $ex;
			return null;
		}
	}
	/**
	数据列表
	return array
	Yii::App()->reader->addL()->gt('userid',0)->lt('userid',4)->addR()->orCond()->eq('sta','异常')->listByPage('dld_backlog', $offset, $limit)
	**/
	public function listByPage($collection,$start = 0,$len = 0,$fields = array()){
		try{
			if($this->_mogoInstance===null){
				$this->_cache=Yii::app()->getComponent($this->cacheId);
				if(!$this->_cache)
					throw new CException(Yii::t('yii','CCacheHttpSession.cacheID is invalid. Please make sure "{id}" refers to a valid cache application component.',array('{id}'=>$this->cacheID)));
				$this->_mogoInstance = new DLDMongoD($this->mongoOptions['host'],$this->mongoOptions['port'],$this->mongoOptions['database']);
			}
			$cursor = $this->_mogoInstance->find($this->criteria(),$collection,$fields);
			$this->clearCondition();
			$total=$cursor->count();
			$cursor = $start>0?$cursor->skip($start):$cursor;
			$cursor = $len>0?$cursor->limit($len):$cursor;
			$cursor = count($this->_sort)?$cursor->sort($this->_sort):$cursor;
			//$cursor->snapshot();
			$response=array('count'=>$total,'rs'=>array());
			while($cursor->hasNext()){
				$row=$cursor->getNext();
                                $row['_mongoId']=$row['_id']->{'$id'};
				unset($row['_id']);
				$response['rs'][]=$row;
			}
			return $response;
		}catch(Exception $ex){
				return array('count'=>0,'rs'=>array());
		}
	}
	/**获得指定查询得记录条数**/
	public function count($collection) {
		try {
			if ($this->_mogoInstance === null) {
				$this->_cache = Yii::app ()->getComponent ( $this->cacheId );
				if (! $this->_cache)
					throw new CException ( Yii::t ( 'yii', 'CCacheHttpSession.cacheID is invalid. Please make sure "{id}" refers to a valid cache application component.', array ('{id}' => $this->cacheID ) ) );
				$this->_mogoInstance = new DLDMongoD ( $this->mongoOptions ['host'], $this->mongoOptions ['port'], $this->mongoOptions ['database'] );
			}
			$result=$this->_mogoInstance->count ( $this->criteria(), $collection );
			$this->clearCondition();
			return $result;
		} catch ( Exception $ex ) {
			return 0;
		}
	}
	/**
	 * 清除查询条件
	 */
	protected function clearCondition(){
		$this->_conds=$this->_attrs=array();
	}
}

?>